<?php

/**
 * finance actions.
 *
 * @package    sf_sandbox
 * @subpackage finance
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class financeActions extends sfActions
{
    /**
     * Executes index action
     *
     */
    public function executeIndex()
    {
        $this->forward('default', 'module');
    }

    public function executePinTransaction()
    {
        if ($this->getRequestParameter('date_from') <> "" || $this->getRequestParameter('date_to') <> "") {
            $c = new Criteria();
            $c->add(TblPinPeer::F_TYPE, array('advance', 'purchase'), Criteria::IN);
            if ($this->getRequestParameter('date_from') <> "") {
                $c->addAnd(TblPinPeer::F_CREATED_DATETIME, $this->getRequestParameter('date_from') . " 00:00:00", Criteria::GREATER_EQUAL);
                $this->date_from = $this->getRequestParameter('date_from');
            }
            if ($this->getRequestParameter('date_to') <> "") {
                $c->addAnd(TblPinPeer::F_CREATED_DATETIME, $this->getRequestParameter('date_to') . " 23:59:59", Criteria::LESS_EQUAL);
                $this->date_to = $this->getRequestParameter('date_to');
            }
            $c->addGroupByColumn('f_dist_id');
            $c->addGroupByColumn('f_cps');
            $this->tbl_pins = TblPinPeer::doSelect($c);
        }
    }

    public function executeDailyBonus()
    {
        if ($this->getRequestParameter('date_from') <> "" || $this->getRequestParameter('date_to') <> "") {
            $query = "SELECT b.f_id,b.f_code,b.f_name,SUM(a.f_dsb) AS f_dsb, SUM(a.f_gdb) AS f_gdb, SUM(a.f_gap) AS f_gap, SUM(a.f_elb) AS f_elb, SUM(a.f_wpb) AS f_wpb, SUM(a.f_dsb+a.f_gdb+a.f_gap+a.f_elb+a.f_wpb) AS f_total FROM tbl_member_comm_sum a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id WHERE 1";
            if ($this->getRequestParameter('date_from') <> "") {
                $query .= " AND f_bonus_date>='" . $this->getRequestParameter('date_from') . "'";
                $this->date_from = $this->getRequestParameter('date_from');
            }
            if ($this->getRequestParameter('date_to') <> "") {
                $query .= " AND f_bonus_date<='" . $this->getRequestParameter('date_to') . "'";
                $this->date_to = $this->getRequestParameter('date_to');
            }
            $query .= " GROUP BY f_dist_id";
            $connection = Propel::getConnection();
            $statement = $connection->prepareStatement($query);
            $this->rs = $statement->executeQuery();
        }
    }

    public function executeCpsPriceSetting()
    {

    }

    public function executeDoSaveCpsPriceSetting()
    {
        $settingId = $this->getRequestParameter('settingId');
        $cps = $this->getRequestParameter('cps');
        $effectiveDate = $this->getRequestParameter('effectiveDate');
        $effectiveTime = $this->getRequestParameter('effectiveTime');
        $status = $this->getRequestParameter('status');

        if (isset($settingId) && trim($settingId) != '') {
            $tbl_cps_price_setting = TblCpsPriceSettingPeer::retrieveByPk($settingId);
            if (!isset($tbl_cps_price_setting)) {
                $output = array(
                    "error" => true,
                    "errorMsg" => "Serious Problem happen in server."
                );
                echo json_encode($output);
                return sfView::HEADER_ONLY;
            }
        } else {
            $tbl_cps_price_setting = new TblCpsPriceSetting();
            $tbl_cps_price_setting->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
        }

        $tbl_cps_price_setting->setFCps($cps);
        $tbl_cps_price_setting->setFEffectiveDate($effectiveDate . " " . $effectiveTime);
        $tbl_cps_price_setting->setStatusCode($status);
        $tbl_cps_price_setting->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));

        $tbl_cps_price_setting->save();

        $output = array(
            "error" => false
        );
        echo json_encode($output);
        return sfView::HEADER_ONLY;
    }

    public function executeAdvancePin()
    {
        $datetime = date("Y-m-d H:i:s");
        $count = $this->getRequestParameter('total_pin');
        $dist_code = $this->getRequestParameter('sponsorId');
        $this->setFlash('successMsg', "");
        $this->setFlash('errorMsg', "");

        if ($count > 0 && $dist_code > 0) {
            $c = new Criteria();
            $c->add(TblDistributorPeer::F_CODE, $dist_code);
            $dist = TblDistributorPeer::doSelectOne($c);
            if ($dist) {
                $c = new Criteria();
                $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);
                $TblSetting = TblSettingPeer::doSelectOne($c);
                if ($TblSetting){
                	$cps = $TblSetting->getFValue();
                }else{
                	$cps = 0.85;
                }

                while ($count > 0) {
                    $fpin = $this->getFPin();

                    $newPin = new TblPin();
                    $newPin->setFDistId($dist->getFId());
                    $newPin->setFPin($fpin);
                    $newPin->setFCPS($cps);
                    $newPin->setFUnit('500');
                    $newPin->setFType('advance');
                    $newPin->setFCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
                    $newPin->setFCreatedDatetime($datetime);
                    $newPin->save();

                    --$count;
                }

                $this->setFlash('successMsg', "Total " . $this->getRequestParameter('total_pin') . " pins credit to " . $dist_code . " with CPS price " . $cps);
            } else {
                $this->setFlash('errorMsg', "Invalid shareholder code");
            }
        }
    }

    public function executeEcashAdjustment()
    {
        $datetime = date("Y-m-d H:i:s");
        $ecash_amount = $this->getRequestParameter('ecash_amount');
        $dist_code = $this->getRequestParameter('sponsorId');
        $ecash_action = $this->getRequestParameter('cbo_action');
        $remark = $this->getRequestParameter('remark');
        $this->setFlash('successMsg', "");
        $this->setFlash('errorMsg', "");

        if ($ecash_amount <> '' && $dist_code > 0) {
            $c = new Criteria();
            $c->add(TblDistributorPeer::F_CODE, $dist_code);
            $dist = TblDistributorPeer::doSelectOne($c);
            if ($dist) {
                $c = new Criteria();
                $c->add(TblAccountPeer::F_DIST_ID, $dist->getFId());
                $c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account = TblAccountPeer::doSelectOne($c);
                if ($tbl_account) {
                    $balance = $tbl_account->getFBalance();
                } else {
                    $tbl_account = new TblAccount();
                    $tbl_account->setFDistId($dist->getFId());
                    $tbl_account->setFType(Globals::ACCOUNT_TYPE_ECASH);
                    $balance = 0;
                }

                $tbl_account_ledger = new TblAccountLedger();
                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setFDistId($dist->getFId());
                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_ADJUSTMENT . ". " . $remark);
                if ($ecash_action == 'credit') {
                    $tbl_account_ledger->setFCredit($ecash_amount);
                    $balance += $ecash_amount;
                } else {
                    $tbl_account_ledger->setFDebit($ecash_amount);
                    $balance -= $ecash_amount;
                }
                $tbl_account_ledger->setFBalance($balance);
                $tbl_account_ledger->setFCreatedDatetime($datetime);
                $tbl_account_ledger->save();

                $tbl_account->setFBalance($balance);
                $tbl_account->save();

                $this->setFlash('successMsg', "Success. " . $dist_code . " ecash balance " . $balance);
            } else {
                $this->setFlash('errorMsg', "Invalid shareholder code");
            }
        }
    }

    public function executePinDetails()
    {
        $c = new Criteria();
        $c->add(TblPinPeer::F_DIST_ID, $this->getRequestParameter('dist_id'));
        if ($this->getRequestParameter('date_from') <> "" && $this->getRequestParameter('date_from') <> 'date_to') {
            $c->addAnd(TblPinPeer::F_CREATED_DATETIME, $this->getRequestParameter('date_from'), Criteria::GREATER_EQUAL);
        }
        if ($this->getRequestParameter('date_to') <> "") {
            $c->addAnd(TblPinPeer::F_CREATED_DATETIME, $this->getRequestParameter('date_to'), Criteria::LESS_EQUAL);
        }
        $c->addAscendingOrderByColumn(TblPinPeer::F_CREATED_DATETIME);
        $this->TblPins = TblPinPeer::doSelect($c);
    }

    public function executeVerifySponsorId()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');

        $c = new Criteria();
        $c->add(TblDistributorPeer::F_CODE, $sponsorId);
        $c->add(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);
        $existUser = TblDistributorPeer::doSelectOne($c);

        $arr = "";
        if ($existUser) {
            $c = new Criteria();
            $c->add(TblAccountPeer::F_DIST_ID, $existUser->getFId());
            $c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);
            $tbl_account = TblAccountPeer::doSelectOne($c);
            if ($tbl_account){ 
            	$balance = $tbl_account->getFBalance();
            }else{ 
            	$balance = 0;
            }

            if ($existUser->getFId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
                $arr = array(
                    'userId' => $existUser->getFUserId(),
                    'userName' => $existUser->getFCode(),
                    'fullname' => $existUser->getFName(),
                    'nickname' => $existUser->getFNickname(),
                    'ecash' => $balance
                );
            }
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    function getFPin()
    {
        while (true) {
            $fpin = rand(0, 999999999999) . "";
            for ($x = 0; $x < (12 - strlen($fpin)); $x++) {
                $fpin = "1" . $fpin;
            }

            $c = new Criteria();
            $c->add(TblPinPeer::F_PIN, $fpin);
            $existPin = TblPinPeer::doSelectOne($c);

            if (!$existPin) {
                break;
            }
        }

        return $fpin;
    }
}
